package fms.core;

import fms.acarsMsgProcessUtil.DownLinkDatagramHeader;
import fms.acarsMsgProcessUtil.RawDatagram;
import fms.xml.FlpRequestXML;
import fms.webservice.Request;
import fms.webservice.XmlUtil;
import org.apache.log4j.Logger;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DownRequestFlp {
    private Logger logger = Logger.getLogger(DownRequestFlp.class);

    private final String regexRequestFlp= "[\\s\\S]*?/CO([\\s\\S]*?)";

    public Request parse(String aContent) {
        logger.info("收到飞行计划请求下行报：\r\n" + aContent);
        logger.debug("[报文解析] 开始进行飞行计划报文解析...");
        Request reqFlp = new Request();
        reqFlp.setServiceType( String.valueOf(ServiceType.FlpRequeest.ordinal()) );
        reqFlp.setVersion("1.0");
        FlpRequestXML reqFlpXml = new FlpRequestXML();
        DownLinkDatagramHeader msgHeader = null;
        String freeText = "";
        try {

            freeText = RawDatagram.GetBody(aContent);

            logger.info("DownRequestFlp:parse 获取正文成功：" + freeText);
            msgHeader = DownLinkDatagramHeader.Parse(RawDatagram.GetHeader(aContent));
            logger.debug("解析报头成功！");
        } catch (Exception e) {
            logger.error(e.getMessage() + "解析报头失败：\r\n" + aContent);
            return null;
        }
        Pattern pattern = Pattern.compile(regexRequestFlp);
        Matcher matcher = pattern.matcher(freeText.trim());
        if (matcher.matches()) {
            logger.debug("开始填充RequsetFlpXml！");
            String routlinename = matcher.group(1);
            reqFlpXml.setRoutlinename(routlinename);
            reqFlpXml.setAircraftid(msgHeader.getAn());
            reqFlpXml.setFlightID(msgHeader.getFi().toString());


        } else {
            logger.error("风温请求信息解析失败，原始报文为：" + aContent);
            return null;
        }
        reqFlp.setRequestXML(XmlUtil.marshallFlpRequest(reqFlpXml) );
		return reqFlp;
	}


}